package com.uminho.egendme;

import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.uminho.exceptions.InvalidOAuthParametersError;
import com.uminho.exceptions.InvalidOAuthTokenError;
import com.uminho.http.Webservice;
import com.uminho.objects.Service;
import com.uminho.service.ServiceCalendar;
import com.uminho.service.ServiceDay;
import com.uminho.tools.Disponibilidades;

/****c* egendme/ServicoActivity
 * DESCRIPTION
 * Classe responsável por oferecer suporte à actividade ServicoActivity
 *
 ****
 */

public class ServicoActivity extends Activity {
	private long serviceId=-1;
	private long bookmarkId=-1;
	private String serviceType="";
	private Service servico=null;
	ProgressDialog myProgressDialog = null; 
	Handler messages;
	ListView listView;
	Button buttonAddFromFavorites, buttonRemoveFromFavorites, buttonAssign, seeServiceCalendar;
	//date piker
	int mYear;
    int mMonth;
    int mDay;
    static final int DATE_DIALOG_ID = 0;
    
	
	/****f* ServicoActivity/onCreate
	 * DESCRIPTION
	 * Método executado para criar a actividade
	 * INPUTS
	 * Estado da aplicação
	 * RESULT
	 * Actividade criada
	 *
	 ****
	 */
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.servico);		
			//set service id
				Bundle b = getIntent().getExtras();
				long sid = b.getLong("servicokey", -1);
				bookmarkId=b.getLong("bookmarkey", -1);
				serviceType=b.getString("servicoType");
				serviceId=sid;
				
	    initHandler();
		
		if(serviceId!=-1)
			initServico();		
		else initEmptyServico();
		
		
	}
	public void setServiceId(long l){
		serviceId=l;
	}
	private void initEmptyServico() {
		messages.sendEmptyMessage(-1);
		
	}
	
	/****f* ServicoActivity/initServico
	 * DESCRIPTION
	 * Método executado para receber o serviço desejado
	 * INPUTS
	 * Id do serviço
	 * RESULT
	 * recebido serviço respectivo
	 *
	 ****
	 */
	private void initServico(){
		myProgressDialog = ProgressDialog.show(this,getString(R.string.loading), getString(R.string.getService), true); 

		Thread a = new Thread() {

			@Override
			public void run() {

				Webservice w = Webservice.getInstance();
				try{
					
					servico=w.getService(serviceId);
						       
	        		
				}catch (InvalidOAuthTokenError e) {
					messages.sendEmptyMessage(-15);
					Log.d("Favorites", "token error loading bookmarks");
					return;
				}catch (InvalidOAuthParametersError e) {
					messages.sendEmptyMessage(-15);
					Log.d("Favorites", "autentication error loading bookmarks");
					return;
				
				}catch (Exception e){
					e.printStackTrace();
					messages.sendEmptyMessage(-16);
					initEmptyServico();
					return;
				}
				Log.d("servico carregou", servico.getName());
				if(servico==null) Log.d("ServicoActivity", "Service é null!!!");
				// dismiss the progress dialog
				myProgressDialog.dismiss();
				messages.sendEmptyMessage(1);

			}

		};
		a.start();
		
	}
	
	/****f* ServicoActivity/initHandler
	 * DESCRIPTION
	 * Método executado para iniciar um handler
	 * RESULT
	 * Handler iniciado
	 *
	 ****
	 */
	private void initHandler(){
		messages = new Handler() {
	        @Override
			public void handleMessage(Message msg) {
	        	//empty
	        	if(msg.what==-1){
	        		Log.d("Servico", "error");
	        		Toast.makeText(ServicoActivity.this, getString(R.string.impossiblereachtheserver), Toast.LENGTH_LONG).show();		      
	        	}
	        	//success
	        	else if(msg.what==1){
	        		//buttons
	        		if(serviceType.equals("favorite")){
	        			//set main layout visible
	        			//LinearLayout generalLayout=(LinearLayout) findViewById(R.id.linearLayoutServicoGeral);
	        			//generalLayout.setVisibility(LinearLayout.VISIBLE);
	        			
	        			ImageView avatar = (ImageView) findViewById(R.id.imageAvatar);
	        			TextView desc, name, email, phone, mobilephone, website, address, category;
	        			LinearLayout ldesc, lname, lemail, lphone, lmobilephone, lwebsite, laddress, lcategory;
	        			
        			    
	        			
	        			buttonRemoveFromFavorites = (Button) findViewById(R.id.buttonRmFavorites);
	        			buttonRemoveFromFavorites.setEnabled(true);
	        			buttonRemoveFromFavorites.setVisibility(View.VISIBLE);
	        			buttonRemoveFromFavorites.setOnClickListener(new OnClickListener() {
		        			public void onClick(View v) {
		        				AlertDialog.Builder builder = new AlertDialog.Builder(ServicoActivity.this);
		        				builder.setMessage(getString(R.string.realy_want_delete))
		        				       .setCancelable(false)
		        				       .setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
		        				           public void onClick(DialogInterface dialog, int id) {
		        				        	   Webservice w = Webservice.getInstance();
		       	        					try{
		       	        						w.delBookmark(bookmarkId);
		       	        					}catch (Exception e){
		       	        						return;
		       	        					}
		       	        					setResult(3);
		       	        					finish();
		       	        					Toast toast = Toast.makeText(ServicoActivity.this,"Remove Favorites", 3000);
		       	        					toast.show();
		        				           }
		        				       })
		        				       .setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
		        				           public void onClick(DialogInterface dialog, int id) {
		        				        	   dialog.cancel();	        				       			
		        				           }
		        				       });
		        				AlertDialog alert = builder.create();
		        				alert.show();
		        				
		        			}
	        			});
	        			//button assign
	        			buttonAssign = (Button) findViewById(R.id.buttonAssign);
	        			buttonAssign.setEnabled(true);
	        			buttonAssign.setVisibility(View.VISIBLE);
	        			buttonAssign.setOnClickListener(new OnClickListener() {
		        			public void onClick(View v) {
		        				/*
		        				 * carregar
		        				 * disponibilidades do
		        				 * serviço
		        				 * 
		        				 */
		        				myProgressDialog = ProgressDialog.show(ServicoActivity.this,getString(R.string.loading), getString(R.string.getService), true); 
		        				Thread a = new Thread() {

		        					@Override
		        					public void run() {

		        					Webservice w = Webservice.getInstance();
		        					try{
		        						GregorianCalendar g = new GregorianCalendar();
		        					/*
		        					 * Get Disponibilidades do serviço do corrente ano
		        					 * 	
		        					 */
		        						
		        					//Disponibilidades.serviceBusyDays = w.getDisponibilidadeAnual(g.get(GregorianCalendar.YEAR), (long) 1);
		        					
		        					
		        					}catch(Exception e){
		        						Log.d("Get disponibilidades exception", e.toString());
		        						e.printStackTrace();
		        					}
		        					
		        					if(Disponibilidades.serviceBusyDays==null)Disponibilidades.serviceBusyDays=new HashMap<Date, Integer>();
		        					
		        					
		        					messages.sendEmptyMessage(60);  
		        					}
		        				};
		        				a.start();
		        				    					
	        					
		        			}
	        			});
	        			
	        		}
	        		
	        		
	        		
	        		Log.d("Servico", "success");
	        		
	        	}
	        	else if(msg.what==-15){
	        		//token/auth error
	        		myProgressDialog.dismiss();
	        		Toast.makeText(ServicoActivity.this, getString(R.string.autentication_error), Toast.LENGTH_LONG).show();
	        	}
	        	else if(msg.what==30){
	        		/*
	        		 * go to calendar
	        		 * 
	        		 * from search
	        		 */
	        		Toast toast = Toast.makeText(ServicoActivity.this,"Assign Favorites"+serviceId, 3000);
					toast.show();
					Log.d("SA-ADD3-serviceid", ""+serviceId);
					Log.d("SA-ADD1-servico null?","servico "+servico.getName()+" id"+servico.getId());		       
					Log.d("SA-ADD2-servico null?", ""+servico.getId());	
					//Service Day
					Intent intent = new Intent(ServicoActivity.this,
							ServiceDay.class);
					Log.d("calendar intent ", servico.getName());
					intent.putExtra("service", servico);
					startActivityForResult(intent, 0);
	        	}
	        	else if(msg.what==31){
	        		Toast.makeText(ServicoActivity.this, getString(R.string.impossiblereachtheserver), Toast.LENGTH_LONG).show();		       
	        		
	        	}
	        	else if(msg.what==60){
	        		/*
	        		 * go to calendar
	        		 * 
	        		 * from favorites
	        		 */
	        		myProgressDialog.dismiss();
					Log.d("SA3-serviceid", ""+serviceId);
					Log.d("SA1-servico null?","servico "+servico.getName()+" id"+servico.getId());		       
					Log.d("SA2-servico null?", ""+servico.getId());	
					//Service Day
					
	        		//go to service calendar
	        		Intent intent2 = new Intent(ServicoActivity.this,
							ServiceCalendar.class);
					Bundle b2 = new Bundle();
					//id of service
					b2.putLong("servicokey", serviceId);
					//id of bookmarker
					b2.putLong("bookmarkey", bookmarkId);
					intent2.putExtra("service", servico);
					Log.d("calendar intent from favirites", servico.getName());
					intent2.putExtras(b2);
					startActivityForResult(intent2, 0); 
	        		  
	        	}
	        	else /*if(msg.what==-16)*/{
	        		//connection error
	        		myProgressDialog.dismiss();
	        		Toast.makeText(ServicoActivity.this, getString(R.string.impossiblereachtheserver), Toast.LENGTH_LONG).show();		       
	        		finish();
	        		//InternalStorage.goLoggin(ServicoActivity.this);
	        	}
	        	if(myProgressDialog.isShowing()) myProgressDialog.dismiss();
	        }
		};
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);   
		Log.d("ServicoActivity result", "req "+requestCode+" res "+resultCode);
	}
	
}
